package com.itheima.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginCheckerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        //1.获取请求url地址

        String url=httpServletRequest.getRequestURI().toString();

        //2.解析url中是否含有login关键字，有则放行
        if (url.contains("login")){
            log.info("登录页面放行");
            return true;
        }
        //3.获取jwt令牌，判断jwt是否为空或空串
        String jwt=httpServletRequest.getHeader("token");
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头为空，返回未登录信息");
            Result result=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(result);
            httpServletResponse.getWriter().write(notLogin);
            return false;
        }
        //4.jwt存在，校验jwt令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析jwt失败，返回未登录信息");
            Result result=Result.error("NOT_LOGIN");
            String notLogin= JSONObject.toJSONString(result);
            httpServletResponse.getWriter().write(notLogin);
            return false;
        }


        //放行
        log.info("解析jwt成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHanler......");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterHandler");
    }
}
